package tcu.iot.mqttupdate.utils.mqttutils;

import org.springframework.context.ApplicationContext;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tcu.iot.mqttupdate.service.MQTTService;

/**
 * MQTT 推送回调
 */
public class MqttPushCallback implements MqttCallback {

    private static final Logger log = LoggerFactory.getLogger(MqttPushCallback.class);

    @Override
    public void connectionLost(Throwable cause) {
        log.info("断开了MQTT连接 ：{}", cause.getMessage());
        log.error(cause.getMessage(), cause);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info(token.isComplete() + "");
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.info("Topic: " + topic);
        log.info("Message: " + new String(message.getPayload()));

        ApplicationContext context = SpringUtils.context;
        MQTTService mqttService = context.getBean(MQTTService.class);

        mqttService.InsertData(topic, new String(message.getPayload()));
    }

}